from socket import *
from tkinter import filedialog,messagebox
import os,json,sys
def Filesender():
    files = filedialog.askopenfilename()
    if files=='':
        print('NO FILES')
        sys.exit()
    print(files)
    file=open(files,'rb')
    data=file.read()
    size=os.path.getsize(files)

    fns=files.split(sep='/')
    fn=fns.pop(-1)

    head={"filesize":size,'filename':fn}
    jsnhead=json.dumps(head)
    try:
        sctsend=socket(AF_INET,SOCK_STREAM)
        sctsend.connect(('172.211.80.127',21100))
        sctsend.send(jsnhead.encode())
        print('OK!')
    except:
        messagebox.showerror('连接取消','对方未就绪')
    else:
        resp=sctsend.recv(1024)
        fr=resp.decode()
        jsnfr=json.loads(fr)
        conf=jsnfr['ready']
        if conf==True:
            sctsend.sendall(data)
            messagebox.showinfo('文件传输','传输完成！')
        elif conf==False:
            messagebox.showerror('连接取消','对方拒收了您的文件')


